<template>
  <div class="login">
    <el-form
      ref="form"
      :model="form"
      label-width="80px"
      label-position="top"
      :rules="rules"
    >
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="form.phone"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit" :loading="isLoginLoading">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { login } from '@/services/user'
export default {
  data () {
    return {
      form: {
        phone: '',
        password: ''
      },
      rules: {
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1\d{10}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 18, message: '密码长度为6到18位', trigger: 'blur' }
        ]
      },
      isLoginLoading: false
    }
  },
  methods: {
    async onSubmit () {
      try {
        // 校验
        await this.$refs.form.validate()
        //
        this.isLoginLoading = true
        //
        const { data } = await login(this.form)
        this.isLoginLoading = false
        if (data.state === 1) {
          // 存储登陆用户信息
          this.$store.commit('setUser', data.content)
          // 登录后跳转到登录前的地址
          this.$router.push(this.$route.query.redirect || '/')
          this.$message({
            type: 'success',
            message: '登录成功'
          })
        }
      } catch (err) {
        this.$message({
          type: 'error',
          message: '登录失败'
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.login {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: cadetblue;
}
.el-form {
  width: 300px;
  padding: 20px;
  background-color: #fff;
  border-radius: 10px;
}
.el-button {
  width: 100%;
}
</style>
